package com.sneakxy.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;

import com.sneakxy.config.Config;
import com.sneakxy.jdbc.JdbcHelper;
import com.sneakxy.utils.StringUtilsExt;

public class ActionAlterSplitTable implements Action {

	private JdbcHelper helper;
	
	private Config config;
	
	@Override
	public void execute(CommandLine command, Options options) throws Exception {
		this.config = createConfig(command, options);
		this.helper = this.config.getJdbc().createJdbcHelper();
		try {
			helper.openConnection();
			String sql = StringUtils.trimToEmpty(config.getTable().getAlterSql());
			int size = config.getTable().getSize();
			String tableOldName = config.getTable().getName();
			String charset = config.getTable().getCharset();
			String alterSql = null;
			String tableName = null;
			List<String> union = new ArrayList<>();
			Map<String, Object> params = new LinkedHashMap<>();
			for(int i=0; i<size; i++) {
				tableName = StringUtils.join(tableOldName, "_", i);
				params.put("tableName", tableName);
				alterSql = StringUtilsExt.replace(sql, params);
				union.add(tableName);
				alterTable(helper, tableName, alterSql);
			}
			String[] alterSqls = helper.getDialect().getAlterTableSql(union, tableOldName, sql, config.getTable().getSql(), charset);
			if(alterSqls != null && alterSqls.length > 0) {
				for(String alter: alterSqls) {
					alterTable(helper, tableOldName, alter);
				}
			} else {
				System.out.println(String.format("请重新创建合并表：%s", tableOldName));
			}
		} catch (ClassNotFoundException e) {
			System.out.println("驱动加载失败.");
		} catch (SQLException e) {
			System.out.println("数据库操作失败.");
			e.printStackTrace();
		} finally {
			if(helper != null) {
				helper.close();
			}
		}
	}
	
	protected void alterTable(JdbcHelper helper, String table, String alterSql) {
		try {
			System.out.println(String.format("执行语句-%s", alterSql));
			helper.update(alterSql);
			System.out.println(String.format("修改%s成功.", table));
		} catch(Exception ex) {
			System.out.println(String.format("修改%s失败.", table));
		}
	}
	
}
